﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PatientManagement.Database;
using PatientManagement.Managers;

namespace PatientManagement
{
    public partial class FormAddTemplate : Form
    {
        private int m_TemplateId;
        public bool IsUpdated;

        public FormAddTemplate(int templateId = 0)
        {
            IsUpdated = false;
            m_TemplateId = templateId;
            InitializeComponent();
            dtgDrug.AutoGenerateColumns = false;
            InitData();
        }

        public void InitData()
        {
            colName.DataSource = ServiceManager.Instance.GetAllGrugs();
            colName.ValueMember = "Id";
            colName.DisplayMember = "Name";
            if (m_TemplateId != 0)
            {
                btnAdd.Text = "Cập nhật";

                var template = ServiceManager.Instance.GetTemplateById(m_TemplateId);
                tbName.Text = template.Name;
                tbDescription.Text = template.Description;

                var details = ServiceManager.Instance.GetPrescriptionTempDetail(m_TemplateId);
                foreach (var detail in details)
                {
                    dtgDrug.Rows.Add(detail.Id, detail.DrugId, Convert.ToInt64(detail.Amount), detail.Usage);
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            IsUpdated = true;
            if (m_TemplateId == 0)
            {
                if (string.IsNullOrEmpty(tbName.Text))
                {
                    errorProvider.SetError(tbName, "Vui lòng nhập tên");
                }
                var template = new PrescriptionTemplate()
                {
                    Name = tbName.Text,
                    Description = tbDescription.Text
                };
                int prescriptionId = ServiceManager.Instance.AddPrescriptionTemplate(template);
                if (prescriptionId > 0)
                {
                    var drugs = new List<Drug>();
                    foreach (DataGridViewRow row in dtgDrug.Rows)
                    {
                        if (row.Cells["colName"].Value != null)
                        {
                            drugs.Add(new Drug()
                            {
                                Id = Convert.ToInt32(row.Cells["colName"].Value),
                                Amount = row.Cells["colVolume"].Value != null ? Convert.ToDecimal(row.Cells["colVolume"].Value) : 0,
                                Description = row.Cells["colUsage"].Value != null ? row.Cells["colUsage"].Value.ToString() : string.Empty
                            });
                        }
                    }
                    ServiceManager.Instance.AddTemplateDetails(drugs, prescriptionId);
                    MessageBox.Show("Thêm thành công");
                    this.Close();
                }
                else
                {
                    MessageBox.Show("Thêm thất bại");
                }
            }
            else
            {
                if (string.IsNullOrEmpty(tbName.Text))
                {
                    errorProvider.SetError(tbName, "Vui lòng nhập tên");
                }
                var template = new PrescriptionTemplate()
                {
                    Name = tbName.Text,
                    Description = tbDescription.Text,
                    Id = m_TemplateId
                };
                var result = ServiceManager.Instance.UpdateTemplate(template);
                if (result)
                {
                    var drugs = new List<Drug>();
                    foreach (DataGridViewRow row in dtgDrug.Rows)
                    {
                        if (row.Cells["colName"].Value != null)
                        {
                            int drugId = Convert.ToInt32(row.Cells["colName"].Value);
                            if (row.Cells["colId"].Value != null)
                            {
                                int id = Convert.ToInt32(row.Cells["colId"].Value);
                                ServiceManager.Instance.UpdateTemplateDetails(new PrescriptionTempDetail()
                                {
                                    Id = id,
                                    DrugId = drugId,
                                    Amount = row.Cells["colVolume"].Value != null ? Convert.ToDecimal(row.Cells["colVolume"].Value) : 0,
                                    Usage = row.Cells["colUsage"].Value != null ? row.Cells["colUsage"].Value.ToString() : string.Empty
                                });
                            }
                            else
                            {
                                drugs.Add(new Drug()
                                {
                                    Id = Convert.ToInt32(row.Cells["colName"].Value),
                                    Amount = row.Cells["colVolume"].Value != null ? Convert.ToDecimal(row.Cells["colVolume"].Value) : 0,
                                    Description = row.Cells["colUsage"].Value != null ? row.Cells["colUsage"].Value.ToString() : string.Empty
                                });
                            }
                        }
                    }
                    ServiceManager.Instance.AddTemplateDetails(drugs, m_TemplateId);
                    MessageBox.Show("Cập nhật thành công");
                    this.Close();
                }
            }
        }

        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control is ComboBox)
            {
                var cbo = e.Control as ComboBox;

                cbo.DropDownStyle = ComboBoxStyle.DropDown;

                cbo.AutoCompleteMode = AutoCompleteMode.SuggestAppend;

                cbo.AutoCompleteSource = AutoCompleteSource.ListItems;
            }
        }

        private void dtgDrug_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (e.ColumnIndex == dtgDrug.Columns["colDelete"].Index)
                {
                    var dialogResult = MessageBox.Show("Bạn có muốn xóa không", "Xác nhận", MessageBoxButtons.YesNo);
                    if (dialogResult == DialogResult.Yes)
                    {
                        if (dtgDrug["colId", e.RowIndex].Value != null)
                        {
                            int id = Convert.ToInt32(dtgDrug["colId", e.RowIndex].Value);
                            var result = ServiceManager.Instance.DeleteTemplateDetails(id);
                            if (result)
                            {
                                dtgDrug.Rows.RemoveAt(e.RowIndex);
                                MessageBox.Show("Xóa thành công");
                            }
                            else
                            {
                                MessageBox.Show("Xóa thất bại");
                            }
                        }
                        else
                        {
                            dtgDrug.Rows.RemoveAt(e.RowIndex);
                            MessageBox.Show("Xóa thành công");
                        }
                    }
                }
            }
        }
    }
}
